<template>
  <XenPageLayout
    title="编辑加班申请"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="编辑加班申请信息"
        :subtitle="`申请单ID: ${overtimeId || 'O12345'}`"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        :showFooter="false"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChange"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @departmentPickerChange="handleDepartmentPickerChange"
        @departmentPickerOpen="handleDepartmentPickerOpen"
        @departmentPickerClose="handleDepartmentPickerClose"
        @dateTimePickerOpen="handleDateTimePickerOpen"
        @dateTimePickerClose="handleDateTimePickerClose"
        @autoCompleteChange="handleAutoCompleteChange"
        @autoCompleteSearch="handleAutoCompleteSearch"
      />
    </view>

    <!-- 固定底部操作按钮 -->
    <XenFormActions
      :actions="formActions"
      :hidden="isDepartmentPickerOpen || isDateTimePickerOpen"
      @action="handleFormAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useOvertimeInfo } from "./composables/useInfo";
// 导入统一事件系统
import { ResignInfoEvents } from "@/utils/eventBus";
// 导入API和接口类型
import SysDailyOvertimeRequestBillApi from "./api/index";
import type { ISysDailyOvertimeRequestBillVm, ISearchByPersonRequest } from "./api/interface";
import { overtimeFormConfig } from "./form-config";
import commonApi from "@/api/common";
import type { ICompanyItem } from "@/type/common";

// 获取路由参数
const overtimeId = ref<string>("");

// 创建API实例
const api = SysDailyOvertimeRequestBillApi();
const commonApiInstance = commonApi();

// 审核权限标识
const isMyApprove = ref<boolean>(false);

// 部门选择器打开状态
const isDepartmentPickerOpen = ref<boolean>(false);

// 时间选择器打开状态
const isDateTimePickerOpen = ref<boolean>(false);

// 排班记录字段是否可用
const isScheduleRecordEnabled = ref<boolean>(false);

// 公司和部门数据
const companyList = ref<ICompanyItem[]>([]);
const departmentList = ref<any[]>([]);

// 动态更新表单分组，根据排班记录字段状态
const formSections = computed(() => {
  const sections = getFormSectionsByPageType("edit");
  
  // 找到包含排班记录字段的分组并更新其状态
  sections.forEach(section => {
    const recordField = section.fields.find(field => field.key === "recordId");
    if (recordField) {
      recordField.disabled = !isScheduleRecordEnabled.value;
      recordField.placeholder = isScheduleRecordEnabled.value ? "请选择排班记录" : "请先选择员工";
    }
  });
  
  return sections;
});

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "save",
    label: isMyApprove.value ? "取消" : "保存",
    type: "success" as const,
  },
  {
    key: "submit",
    label: "提交",
    type: "primary" as const,
  },
]);

// 使用加班申请信息 Composable
const {
  formData,
  formErrors,
  pickerValues,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  initializeOptions,
  loadOvertimeDetail,
  search,
  originalData,
  convertFormDataToApiFormatForEdit,
  saveOvertime,
} = useOvertimeInfo();

// 计算加班时长
const calculateOvertimeHours = () => {
  if (formData.startTime && formData.endTime) {
    const startTime = new Date(formData.startTime);
    const endTime = new Date(formData.endTime);
    
    if (endTime > startTime) {
      const diffInMs = endTime.getTime() - startTime.getTime();
      const diffInHours = diffInMs / (1000 * 60 * 60);
      formData.overtimeHours = Math.round(diffInHours * 100) / 100; // 保留两位小数
    } else {
      formData.overtimeHours = 0;
    }
  }
};

// 监听开始时间和结束时间变化，自动计算加班时长
watch([() => formData.startTime, () => formData.endTime], () => {
  calculateOvertimeHours();
});

// 根据公司ID获取公司名称
const getCompanyNameById = (orgId: string | null): string => {
  if (!orgId || !companyList.value.length) return "";

  const company = companyList.value.find((item) => item.Value === orgId);
  return company ? company.Text : "";
};

// 根据部门ID获取部门名称（递归查找，支持多级部门）
const getDepartmentNameById = (groupId: string | null): string => {
  if (!groupId || !departmentList.value.length) return "";

  // 递归查找部门
  const findDepartmentById = (departments: any[], id: string): any => {
    for (const dept of departments) {
      if (dept.ID === id || dept.Value === id) {
        return dept;
      }
      if (dept.Children && dept.Children.length > 0) {
        const found = findDepartmentById(dept.Children, id);
        if (found) return found;
      }
    }
    return null;
  };

  const department = findDepartmentById(departmentList.value, groupId);
  return department
    ? department.Text || department.GroupName || department.Name
    : "";
};

// 加载公司列表
const loadCompanyList = async () => {
  const response = await commonApiInstance.GetUserCompanies();
  if (response && Array.isArray(response)) {
    companyList.value = response;
  }
};

// 加载部门列表
const loadDepartmentList = async () => {
  const response = await commonApiInstance.GetParentsTree();
  if (response && Array.isArray(response)) {
    departmentList.value = response;
  }
};

// 处理公司信息显示
const processCompanyInfo = () => {
  if (originalData.value && originalData.value.OrgId) {
    const companyName = getCompanyNameById(originalData.value.OrgId);
    if (companyName) {
      formData.orgName = companyName;
    }
  }
};

// 处理部门信息显示
const processDepartmentInfo = () => {
  if (originalData.value && originalData.value.GroupId) {
    const departmentName = getDepartmentNameById(originalData.value.GroupId);
    if (departmentName) {
      formData.groupName = departmentName;
    }
  }
};

// 执行排班记录回显
const performRecordIdEcho = () => {
  if (!originalData.value?.RecordId || !overtimeFormConfig.recordId?.optionsData) {
    return;
  }

  const recordId = originalData.value.RecordId;
  const scheduleOptions = overtimeFormConfig.recordId.optionsData;

  const selectedRecord = scheduleOptions.find(
    (option: any) => option.value === recordId
  );

  if (selectedRecord) {
    formData.recordId = selectedRecord.text;
    pickerValues.recordId = selectedRecord.value;
  }
};

// 加载排班记录
const loadScheduleRecords = async (personId: string) => {
  if (!personId) return;

  try {
    // 构建查询参数
    const today = new Date();
    const startDate = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    const endDate = today.toISOString().split('T')[0];

    const params: ISearchByPersonRequest = {
      PersonId: personId,
      Page: 1,
      Limit: 100,
      IsPlainText: true,
      IsEmunToString: true,
      ShiftDate: [startDate, endDate],
    };

    // 调用排班记录查询接口
    const response = await api.searchByPerson(params);

    // 处理返回的排班记录数据
    if (
      response &&
      response.Data &&
      response.Data[0] &&
      response.Data[0].Records &&
      Array.isArray(response.Data[0].Records)
    ) {
      // 过滤掉AttendanceResult为"未计算"的数据
      const filteredRecords = response.Data[0].Records.filter((item: any) => 
        item.AttendanceResult !== "未计算"
      );
      
      const scheduleOptions = filteredRecords.map((item: any) => ({
        value: item.ID || item.Id,
        text: `${item.ShiftDate || ""} ${item.AttendanceShiftGroupName || ""} (${item.ShiftInfo || ""})`,
      }));

      // 更新配置中的选项数据
      if (overtimeFormConfig.recordId) {
        overtimeFormConfig.recordId.optionsData = scheduleOptions;
        overtimeFormConfig.recordId.options = scheduleOptions.map(
          (item: any) => item.text,
        );
      }
      
      // 启用排班记录字段
      isScheduleRecordEnabled.value = true;
    } else {
      // 没有排班记录
      if (overtimeFormConfig.recordId) {
        overtimeFormConfig.recordId.optionsData = [];
        overtimeFormConfig.recordId.options = [];
      }
      
      // 禁用排班记录字段
      isScheduleRecordEnabled.value = false;
    }
  } catch (error) {
    console.error("加载排班记录失败:", error);
    uni.showToast({
      title: "加载排班记录失败",
      icon: "none",
    });
  }
};

// 加载排班记录用于编辑页回显
const loadScheduleRecordsForEdit = async (personId: string) => {
  if (!personId) return;

  try {
    // 构建查询参数
    const today = new Date();
    const startDate = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    const endDate = today.toISOString().split('T')[0];

    const params: ISearchByPersonRequest = {
      PersonId: personId,
      Page: 1,
      Limit: 100,
      IsPlainText: true,
      IsEmunToString: true,
      ShiftDate: [startDate, endDate],
    };

    // 调用排班记录查询接口
    const response = await api.searchByPerson(params);

    // 处理返回的排班记录数据
    if (
      response &&
      response.Data &&
      response.Data[0] &&
      response.Data[0].Records &&
      Array.isArray(response.Data[0].Records)
    ) {
      // 过滤掉AttendanceResult为"未计算"的数据
      const filteredRecords = response.Data[0].Records.filter((item: any) => 
        item.AttendanceResult !== "未计算"
      );
      
      const scheduleOptions = filteredRecords.map((item: any) => ({
        value: item.ID || item.Id,
        text: `${item.ShiftDate || ""} ${item.AttendanceShiftGroupName || ""} (${item.ShiftInfo || ""})`,
      }));

      // 更新配置中的选项数据
      if (overtimeFormConfig.recordId) {
        overtimeFormConfig.recordId.optionsData = scheduleOptions;
        overtimeFormConfig.recordId.options = scheduleOptions.map(
          (item: any) => item.text,
        );
      }
      
      // 启用排班记录字段
      isScheduleRecordEnabled.value = true;

      // 回显逻辑已移到 performRecordIdEcho 函数中
    } else {
      // 没有排班记录
      if (overtimeFormConfig.recordId) {
        overtimeFormConfig.recordId.optionsData = [];
        overtimeFormConfig.recordId.options = [];
      }
    }
  } catch (error) {
    console.error("加载排班记录失败:", error);
  }
};

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 部门选择器变化处理
const handleDepartmentPickerChange = (
  fieldKey: string,
  value: string,
  _item: any,
) => {
  formData[fieldKey] = value;
  pickerValues[fieldKey] = value;
  validateField(fieldKey);
};

// 部门选择器弹框打开处理
const handleDepartmentPickerOpen = () => {
  isDepartmentPickerOpen.value = true;
};

// 部门选择器弹框关闭处理
const handleDepartmentPickerClose = () => {
  isDepartmentPickerOpen.value = false;
};

// 时间选择器弹框打开处理
const handleDateTimePickerOpen = () => {
  isDateTimePickerOpen.value = true;
};

// 时间选择器弹框关闭处理
const handleDateTimePickerClose = () => {
  isDateTimePickerOpen.value = false;
};

// 自动补全变化处理
const handleAutoCompleteChange = async (
  fieldKey: string,
  _value: string,
  option: any,
) => {
  if (option) {
    formData[fieldKey] = option.text;
    pickerValues[fieldKey] = option.value;

    // 如果是员工选择，自动填入员工工号、姓名、公司和部门信息，并加载排班记录
    if (fieldKey === "personId" && option.subtitle) {
      const staffNoMatch = option.subtitle.match(/工号:\s*(\S+)/);
      if (staffNoMatch) {
        formData.staffNo = staffNoMatch[1];
      }
      formData.name = option.text;

      if (option.extData) {
        formData.orgName = option.extData.orgName || "";
        formData.groupName = option.extData.groupName || "";
        pickerValues.orgId = option.extData.orgId || "";
        pickerValues.groupId = option.extData.groupId || "";
        formData.orgId = option.extData.orgId || "";
        formData.groupId = option.extData.groupId || "";
      }

      // 加载该员工的排班记录
      await loadScheduleRecords(option.value);
    }
  } else {
    formData[fieldKey] = "";
    pickerValues[fieldKey] = "";

    // 如果清空员工选择，也清空排班记录
    if (fieldKey === "personId") {
      formData.staffNo = "";
      formData.name = "";
      formData.orgName = "";
      formData.groupName = "";
      formData.orgId = "";
      formData.groupId = "";
      pickerValues.orgId = "";
      pickerValues.groupId = "";
      
      // 清空排班记录
      formData.recordId = "";
      pickerValues.recordId = "";
      
      // 清空排班记录选项并禁用
      if (overtimeFormConfig.recordId) {
        overtimeFormConfig.recordId.optionsData = [];
        overtimeFormConfig.recordId.options = [];
      }
      
      // 禁用排班记录字段
      isScheduleRecordEnabled.value = false;
    }
  }

  validateField(fieldKey);
};

// 自动补全搜索处理
const handleAutoCompleteSearch = async (fieldKey: string, query: string) => {
  console.log("搜索:", fieldKey, query);
};

// 页面加载时获取数据
onMounted(async () => {
  await initializeOptions();
  await loadCompanyList();
  await loadDepartmentList();
});

// 路由参数处理
onLoad((options: any) => {
  if (options.id) {
    overtimeId.value = options.id;
    loadOvertimeDetail(options.id).then(async () => {
      processCompanyInfo();
      processDepartmentInfo();
      
      // 如果已有员工数据，加载排班记录用于回显
      if (pickerValues.personId || originalData.value?.PersonId) {
        const personId = pickerValues.personId || originalData.value?.PersonId;
        if (personId) {
          await loadScheduleRecordsForEdit(personId);
          
          // 加载完排班记录后，进行回显
          await nextTick(); // 确保DOM更新完成
          performRecordIdEcho();
        }
      }
    });
  }
});

// 图片上传处理
const handleImageUpload = async (field: any, event: any) => {
  console.log("图片上传:", field.key, event);
};

const handleImageSuccess = (_field: any, _event: any) => {};

const handleImageFail = (_field: any, _event: any) => {};

const handleImageDelete = (field: any, event: any) => {
  console.log("图片删除:", field.key, event);
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {};

const handleFileSuccess = (_field: any, _event: any) => {};

const handleFileFail = (_field: any, _event: any) => {};

const handleFileDelete = (_field: any, _event: any) => {};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "save":
      handleSave();
      break;
    case "submit":
      handleSubmit();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 保存表单
const handleSave = async () => {
  uni.showLoading({ title: "保存中..." });

  try {
    // 使用 saveOvertime 方法，它会进行表单验证并正确处理数据格式
    const result = await saveOvertime();

    uni.hideLoading();

    if (result.success && result.data && result.data.ID) {
      const searchResponse = await search({});
      if (searchResponse && searchResponse.length > 0) {
        ResignInfoEvents.emit("refresh", {
          id: result.data.ID,
          data: searchResponse,
          customAction: "edit",
        });
      }

      uni.showToast({
        title: "保存成功",
        icon: "success",
        success: () => {
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        },
      });
    } else {
      let errorMessage = "保存失败，请重试";

      if (result.error) {
        errorMessage = result.error;
      } else if (result.validation?.firstErrorMessage) {
        errorMessage = result.validation.firstErrorMessage;
      }

      uni.showToast({
        title: errorMessage,
        icon: "none",
        duration: 3000,
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("保存失败:", error);
    uni.showToast({
      title: "保存失败，请重试",
      icon: "none",
      duration: 2000,
    });
  }
};

// 提交表单
const handleSubmit = async () => {
  uni.showLoading({ title: "提交中..." });

  try {
    const apiData: ISysDailyOvertimeRequestBillVm = {
      Entity: convertFormDataToApiFormatForEdit(),
      ActionName: "Submit",
      IsMyApprove: isMyApprove.value,
      Remark: formData.remark || "",
    };

    const response = await api.approve(apiData);

    uni.hideLoading();

    if (response && response.ID) {
      const searchResponse = await search({});
      if (searchResponse && searchResponse.length > 0) {
        ResignInfoEvents.emit("refresh", {
          id: response.ID,
          data: searchResponse,
          customAction: "edit",
        });
      }

      uni.showToast({
        title: "提交成功",
        icon: "success",
        success: () => {
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        },
      });
    } else {
      uni.showToast({
        title: "提交失败，请重试",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "提交失败，请重试",
      icon: "none",
      duration: 2000,
    });
  }
};
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}
</style>
